/** Created By wene<354007048@qq.com> . Date at 2020/5/4 */
package common

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
	"github.com/jinzhu/gorm"
	"main/models"
	"math"
	"net/http"
)

type PageVo struct {
	data       interface{}
	totalLimit int
	totalPage  int
	page       int
	limit      int
}

func Paginate(m interface{}, page int, limit int) (res *gorm.DB, _ int, _ int) {
	if page <= 0 {
		page = 0
	}
	if limit <= 0 {
		limit = 10
	}
	startLine := page * limit
	return models.DB.Offset(startLine).Limit(limit).Find(m), page, limit
}

func ReturnPageDate(c *gin.Context, result *gorm.DB, page int, limit int) {
	c.JSON(http.StatusOK,gin.H{
		"data":       result.Value,
		"totalLimit": result.RowsAffected,
		"totalPage":  math.Ceil(float64(int(result.RowsAffected) / limit)),
		"page":       page,
		"limit":      limit,
	})
}

func ReturnSuccess(c *gin.Context, data interface{}, msg string, code int){
	c.JSON(http.StatusBadRequest,gin.H{
		"msg":       msg,
		"code":       code,
		"data":       data,
	})
}

func ReturnError(c *gin.Context, msg string, code int){
	c.JSON(http.StatusBadRequest,gin.H{
		"msg":       msg,
		"code":       code,
		"data":       nil,
	})
}

func Validator(form interface{}, batch bool) (Obj interface{}, err error) {
	var uni      *ut.UniversalTranslator
	var validate *validator.Validate

	zh := zh.New()
	uni = ut.New(zh, zh)

	trans, _ := uni.GetTranslator("zh")
	validate = validator.New()
	zh_translations.RegisterDefaultTranslations(validate, trans)

	if err := validate.Struct(form); err != nil {
		errs := err.(validator.ValidationErrors)
		return form, getValidateError(errs, trans,batch)
	}
	return form,nil
}


func getValidateError(errs validator.ValidationErrors, trans ut.Translator, batch bool) (err error)  {
	var msg string // 错误内容
	var splice = "," // 错误链接符

	for index, e := range errs {
		msg += fmt.Sprintf("%v",e.Translate(trans))
		if batch == false && index == 0 {
			break
		}
		if index < len(errs) -1 {
			msg += splice
		}
	}

	return errors.New(msg)
}